import paramiko
import pexpect
import os
from pexpect import pxssh

def install_desktop_and_vnc(hostname, username, password):
    try:
        # 使用paramiko建立SSH连接
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(hostname, username=username, password=password)
        
        # 使用pexpect通过ssh执行命令
        s = pxssh.pxssh(timeout=30)  # 设置超时时间为30秒
        if not s.login(hostname, username, password):
            print("SSH session failed on login.")
            print(str(s))
        else:
            print("SSH session login successful")
            # 安装桌面环境，这里以Ubuntu的GNOME桌面为例
            s.sendline('sudo apt-get update')
            if not s.prompt(timeout=100):  # 增加超时时间，等待较长的命令完成
                print("Timeout or error in updating packages.")
                return
            s.sendline('sudo apt-get install xfce4 xfce4-goodies -y')
            if not s.prompt(timeout=1200):  # 安装桌面可能需要更长时间
                print("Timeout or error in installing xfce4-desktop.")
                return
            
            # 安装VNC服务器
            s.sendline('sudo apt-get install tightvncserver -y')
            if not s.prompt(timeout=60):
                print("Timeout or error in installing VNC server.")
                return
            
            # 设置VNC访问密码
            s.sendline('vncserver')
            if s.expect('Password', timeout=30):
                print("Timeout or error waiting for password prompt.")
                return
            s.sendline('your_vnc_password')  # 替换为你的VNC密码
            if s.expect('Verify:', timeout=30):
                print("Timeout or error waiting for password verification prompt.")
                return
            s.sendline('your_vnc_password')  # 再次输入你的VNC密码
            if s.expect('Would you like to enter a view-only password (y/n)?', timeout=30):
                print("Timeout or error waiting for view-only password prompt.")
                return
            s.sendline('n')
            if not s.prompt(timeout=30):
                print("Timeout or error after setting VNC password.")
                return
            
            print("Desktop and VNC server installed successfully.")
            s.logout()
    except pxssh.ExceptionPxssh as e:
        print("pxssh failed on login.")
        print(e)
    except Exception as e:
        print("An error occurred: ", e)

# 使用实际的hostname, username, password调用函数
install_desktop_and_vnc('localhost', 'ubuntu', 'Ubuntu')